import axios from 'axios';
import { getAuth, removeAuth, setAuth } from './storage';
import { Toast } from 'antd-mobile';
import history from './history';

// 请求基地址
export const baseURL = 'http://geek.itheima.net';

const request = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    const token = getAuth().token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    //处理响应错误
    // 1.网络错误
    if (!error.response) {
      Toast.show({ content: '网络出错了，请稍后重试' });
      return Promise.reject(error);
    }
    // 3.非401
    if (error.response.status !== 401) {
      Toast.show({ content: error.response.data.msg });
      return Promise.reject(error);
    }
    //2.用户权限过期 401
    const { token, refresh_token } = getAuth();
    // 2.1 无token
    if (!token) {
      Toast.show({ content: '请先登录' });
      history.push('/login');
      return Promise.reject(error);
    }
    // 2.2 有token 无refresh_token
    if (!refresh_token) {
      Toast.show({ content: '登录失效，请重新登录' });
      history.push('/login');
      return Promise.reject(error);
    }
    //2.3有token但是过期，也有refreshtoken 获取新的token
    try {
      const res = await axios({
        url: baseURL + '/v1_0/authorizations',
        method: 'put',
        headers: { Authorization: `Bearer ${refresh_token}` },
      });
      // 2.5.1 更新token
      const newToken = res.data.data.token;
      setAuth({ token: newToken, refresh_token: refresh_token });
      // 2.5.2 重新发起请求
      return request(error.config);
    } catch (err) {
      // 2.4 处理refresh_token过期 跳转登录
      console.dir(err);
      Toast.show({ content: '登录失效，请重新登录' });
      //清空token信息
      removeAuth();
      history.push('/login');
      return Promise.reject(error);
    }
  }
);

export default request;
